/*
    网络服务：负责与前端交互
    1、根据请求，调用searcher模块获取资源，构建应答
*/
#include "searcher.hpp"
#include "/home/whl/third_part/cpp-httplib-v0.7.15/httplib.h"


const std::string parsed_result_filepath = "doc/parsed_html/parsed_results.txt"; // 保存解析结果的文件
const std::string root_path = "./wwwroot";
const std::string response_html_filepath = "./wwwroot/response_html/response.html";

int main()
{
    // 1、定义一个网络服务
    httplib::Server svr;
    svr.set_base_dir(root_path.c_str()); //设置web根目录

    // 2、预绑定资源
    ns_searcher::Searcher s;
    s.initSearcher(parsed_result_filepath);
    svr.Get("/search", [&s](const httplib::Request& req, httplib::Response& rsp){
        std::string word = req.get_param_value("word");
        if(word.size() == 0)
        {
            std::string html;
            if(!ns_util::FileUtil::readFile(response_html_filepath, &html))
                LOG(ERROR, "应答html构建失败\n");
            rsp.set_content(html, "text/html;charset=utf-8");
            return;
        }
        std::string json_str;
        s.searchQuery(word, &json_str); //搜索
        rsp.set_content(json_str, "application/json");
    });
    
    LOG(INFO, "服务启动......\n");
    svr.listen("0.0.0.0", 8888);
    return 0;
}